#!/bin/bash

# 定义变量
binname=wechat-universal
pkgname=${binname}-bwrap
pkgver=1.0.0.241
srcdir=$(pwd)
pkgdir=$(pwd)/${pkgname}

binroot=opt/apps/com.tencent.wechat/files

echo "Creating package directory"

if [ -d ${pkgdir} ]; then
  rm -rf ${pkgdir}
fi

mkdir -p ${pkgdir}/DEBIAN
mkdir -p ${pkgdir}/usr/lib/license # 我们虽然这里不直接将license放在这里，但是这个目录是必须的，因为启动时需要使用到这个目录
mkdir -p ${pkgdir}/${binroot}/license
mkdir -p ${pkgdir}/usr/share/applications


# 下载UOS版微信
echo "Downloading source files..."
wget -O ${binname}-uos.deb "https://home-store-packages.uniontech.com/appstore/pool/appstore/c/com.tencent.wechat/com.tencent.wechat_${pkgver}_amd64.deb"

echo "Extract ${binname} deb file"
dpkg -x ${binname}-uos.deb ${pkgdir}/

echo "Fixing licenses"
cp -r ./libuosdevicea.so ${pkgdir}/${binroot}/license
cp -r ./libcrypto.so.1.1 ${pkgdir}/${binroot} # libuosdevicea.so 需要依赖 libcrypto.so.1.1
tar -zxvf license.tar.gz
cp -r license/* ${pkgdir}/${binroot}/license/

echo "启动脚本"
cp wechat.sh ${pkgdir}/${binroot}/wechat.sh
chmod +x ${pkgdir}/${binroot}/wechat


echo "Installing stuff in place"
rm ${pkgdir}/${binroot}/../entries/applications/*.desktop
cp ${binname}.desktop ${pkgdir}/${binroot}/../entries/applications
cp ${binname}.desktop ${pkgdir}/usr/share/applications
cp wechat.sh "${pkgdir}/${binroot}/wechat.sh"
chmod +x "${pkgdir}/${binroot}/wechat.sh"

# 创建控制文件
cat <<EOF > ${pkgdir}/DEBIAN/control
Package: $pkgname
Version: $pkgver
Section: custom
Priority: optional
Architecture: amd64
Depends: libnss3, xdg-utils, libxss1, libnotify4, bubblewrap, xdg-desktop-portal, openssl, lsb-release
Maintainer: leaeasy <leaeasy at gmail dot com>
Description: WeChat Testing with bwrap sandbox
EOF

# 创建postinst文件
cat <<EOF > ${pkgdir}/DEBIAN/postinst
#!/bin/bash
set -e
if [ -x /usr/bin/update-desktop-database ]; then
  update-desktop-database
fi
if [ -x /usr/bin/update-mime-database ]; then
  update-mime-database /usr/share/mime
fi
exit 0
EOF

# 创建postrm文件
cat <<EOF > ${pkgdir}/DEBIAN/postrm
#!/bin/bash
set -e
if [ -x /usr/bin/update-desktop-database ]; then
  update-desktop-database
fi
if [ -x /usr/bin/update-mime-database ]; then
  update-mime-database /usr/share/mime
fi
exit 0
EOF

chmod 755 ${pkgdir}/DEBIAN/postinst
chmod 755 ${pkgdir}/DEBIAN/postrm

# 构建.deb包
dpkg-deb --build ${pkgdir}
echo "Deb package built at ${pkgdir}.deb"

